Imports System.IO
Imports System.Data
Imports Microsoft.VisualBasic
Imports System.DirectoryServices

Public Class adsiClass

    Public userName, userPassword As String

    Public Function ExtractUserName(ByVal path As String) As String
        Dim userPath As String() = path.Split(New Char() {"\"c})
        Return userPath((userPath.Length - 1))
    End Function

    Public Function ExtractUserNameFromLoginName(ByVal loginName As String) As String
        Dim newLoginName As String
        If loginName.Contains("\") Then
            Dim name As String = loginName
            Dim nameAr() As String = name.Split("\")
            newLoginName = nameAr(1)
        ElseIf loginName.Contains("@") Then
            Dim name As String = loginName
            Dim nameAr() As String = name.Split("@")
            newLoginName = nameAr(0)
        End If
        Return newLoginName
    End Function

    Function GetDirectoryEntry(ByVal st As String) As DirectoryEntry
        Dim de2 As New DirectoryEntry()
        de2.Path = st
        de2.Username = userName
        de2.Password = userPassword
        
        de2.AuthenticationType = AuthenticationTypes.FastBind
        Return de2
    End Function

    Public Sub SetPassword(ByVal path As String, ByVal newPassword As String)
        Dim usr As New DirectoryEntry()
        usr.Path = path
        usr.Username = userName
        usr.Password = userPassword
        usr.AuthenticationType = AuthenticationTypes.Secure
        Dim password As Object() = New Object() {newPassword}
        Dim ret As Object = usr.Invoke("SetPassword", password)
        usr.CommitChanges()
        usr.Close()
    End Sub

    Public Function SetSecurePassword(ByVal newPassword1 As String) As String
        Return newPassword1
    End Function

    Sub disableUser(ByVal path As String)
        Dim dey As DirectoryEntry = GetDirectoryEntry(path)
        Dim val As Integer = CInt(dey.Properties("userAccountControl").Value)
        dey.Properties("userAccountControl").Value = val Or 2
        dey.Properties("msExchHideFromAddressLists").Value = "TRUE"
        dey.CommitChanges()
        dey.Close()
    End Sub

    Sub EnableAccount(ByVal path As String)
        'UF_DONT_EXPIRE_PASSWD 0x10000 
        Dim dey As DirectoryEntry = GetDirectoryEntry(path)
        Dim exp As Integer = CInt(dey.Properties("userAccountControl").Value)
        dey.Properties("userAccountControl").Value = exp Or 1
        dey.CommitChanges()
        'UF_ACCOUNTDISABLE 0x0002 
        Dim val As Integer = CInt(dey.Properties("userAccountControl").Value)
        dey.Properties("userAccountControl").Value = val And Not 2
        dey.CommitChanges()
    End Sub

    Sub AddUserToGroup(ByVal de As DirectoryEntry, ByVal userPath As String, ByVal GroupName As String)
        Dim deUser As DirectoryEntry = GetDirectoryEntry(userPath)
        Dim deSearch As New DirectorySearcher()
        deSearch.SearchRoot = de
        deSearch.Filter = "(&(objectClass=group) (cn=" & GroupName & "))"
        Dim results As SearchResultCollection = deSearch.FindAll()
        Dim isGroupMember As Boolean = False
        If results.Count > 0 Then
            'MsgBox(results(0).Path)
            Dim group As DirectoryEntry = GetDirectoryEntry(results(0).Path)
            Dim userToAdd As String = deUser.Properties("distinguishedName").Value
            If Not group.Properties("member").Contains(userToAdd) Then
                group.Properties("member").Add(deUser.Properties("distinguishedName").Value)
                group.CommitChanges()
            Else
                '''''User Already Exists in specified Group'''''''''

            End If
        End If
        Return
    End Sub

    Sub RemoveUserFromGroup(ByVal de As DirectoryEntry, ByVal userPath As String, ByVal GroupName As String)
        Dim deUser As DirectoryEntry = GetDirectoryEntry(userPath)
        Dim deSearch As New DirectorySearcher()
        deSearch.SearchRoot = de
        deSearch.Filter = "(&(objectClass=group) (cn=" & GroupName & "))"
        Dim results As SearchResultCollection = deSearch.FindAll()
        Dim isGroupMember As Boolean = False
        If results.Count > 0 Then
            'MsgBox(results(0).Path)
            Dim group As DirectoryEntry = GetDirectoryEntry(results(0).Path)
            Dim userToAdd As String = deUser.Properties("distinguishedName").Value
            If group.Properties("member").Contains(userToAdd) Then
                group.Properties("member").Remove(deUser.Properties("distinguishedName").Value)
                group.CommitChanges()
            Else
                '''''User Doesn't Exists in specified Group'''''''''

            End If
        End If
        Return
    End Sub

    Function UserExistInGroup(ByVal de As DirectoryEntry, ByVal userPath As String, ByVal GroupName As String) As Boolean
        Dim res As Boolean
        Dim deUser As DirectoryEntry = GetDirectoryEntry(userPath)
        Dim deSearch As New DirectorySearcher()
        deSearch.SearchRoot = de
        deSearch.Filter = "(&(objectClass=group) (cn=" & GroupName & "))"
        Dim results As SearchResultCollection = deSearch.FindAll()
        Dim isGroupMember As Boolean = False
        If results.Count > 0 Then
            'MsgBox(results(0).Path)
            Dim group As DirectoryEntry = GetDirectoryEntry(results(0).Path)
            Dim userToAdd As String = deUser.Properties("distinguishedName").Value
            If group.Properties("member").Contains(userToAdd) Then
                res = True
            Else
                res = False

            End If
        End If
        Return res
    End Function

    Public Function SaveTextToFile(ByVal strData As String) As Boolean
        Dim fullPath As String
        Dim timeString As String
        timeString = Now.ToLongTimeString.ToString.Replace(":", "-")
        fullPath = "c:\galmod_log\" & Now.ToLongDateString & " " & timeString & ".txt"

        'MsgBox(FullPath)
        strData += vbNewLine & "Evnironment User --> " & Environment.UserName
        Try
            MkDir("c:\galmod_log")
        Catch ex As IOException

        End Try

        Dim Contents As String
        Dim bAns As Boolean = False
        Dim objReader As StreamWriter
        Try


            objReader = New StreamWriter(fullPath)
            objReader.Write(strData)
            objReader.Close()
            bAns = True
        Catch Ex As Exception


        End Try
        Return bAns
    End Function

    Public Sub SetProperty(ByVal de1 As DirectoryEntry, ByVal PropertyName As String, ByVal PropertyValue As String)
        Try
            If PropertyValue IsNot Nothing Then
                If de1.Properties.Contains(PropertyName) Then
                    de1.Properties(PropertyName)(0) = PropertyValue
                Else
                    de1.Properties(PropertyName).Add(PropertyValue)
                End If
            End If
        Catch ex As Exception
            SaveTextToFile(Now.ToLongDateString & " " & Now.ToLongTimeString & vbNewLine & ex.Message.ToString & vbNewLine & "Directory Entry --> " & de1.Path.ToString & vbNewLine & "Property Name--> " & PropertyName & vbNewLine & "Property Value--> " & PropertyValue)
        End Try

    End Sub


    Public Function ExtractCN(ByVal rootDirectory As DirectoryEntry, ByVal distinguishedName As String) As String
        Dim deUser As DirectoryEntry = GetDirectoryEntry(rootDirectory.Path)
        Dim deSearch As New DirectorySearcher()
        deSearch.SearchRoot = rootDirectory
        deSearch.Filter = "(&(objectClass=group) (distinguishedName=" & distinguishedName & "))"
        Dim results As SearchResult = deSearch.FindOne
        Return results.Properties("CN").Item(0).ToString
    End Function

End Class
